package com.jinglvhuanjing.app;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Layout;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.AppCompatTextView;

import com.jinglvhuanjing.app.base.BaseActivity;
import com.jinglvhuanjing.app.bean.LogEvent;
import com.jinglvhuanjing.app.bean.RunEvent;
import com.jinglvhuanjing.app.utils.ByteUtil;
import com.jinglvhuanjing.app.utils.Constants;
import com.jinglvhuanjing.app.utils.LOG;
import com.jinglvhuanjing.app.utils.LogRecordUtil;
import com.jinglvhuanjing.app.utils.SerialMsgHandler;
import com.jinglvhuanjing.app.utils.SingletonSerl;
import com.jinglvhuanjing.app.utils.SpUtils;
import com.jinglvhuanjing.app.utils.StringUtils;
import com.jinglvhuanjing.app.widget.ParamSettingRow1View;
import com.jinglvhuanjing.app.widget.ParamSettingRow2View;
import com.jinglvhuanjing.app.widget.ParamSettingRow3SecView;
import com.jinglvhuanjing.app.widget.ParamSettingRow4SecView;
import com.jinglvhuanjing.app.widget.ParamSettingRow5SecView;
import com.jinglvhuanjing.app.widget.ParamSettingRow6SecView;
import com.jinglvhuanjing.app.widget.SignalOutPanelView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;

public class SettingParamActivity extends BaseActivity {

    private static final String TAG = SettingParamActivity.class.getSimpleName();

    public static void startActivity(Activity activity) {
        Intent intent = new Intent(activity, SettingParamActivity.class);
        activity.startActivity(intent);
    }

    public static void startActivity(Context activity) {
        Intent intent = new Intent(activity, SettingParamActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_setting_params;
    }

    /*** 第1行参数设置 - 4个参数设置 ***/
    private ParamSettingRow1View param_layout1;
    /*** 第2行参数设置 - 4个参数设置 ***/
    private ParamSettingRow2View param_layout2;
    /*** 第3行参数设置 - 运行状态 ***/
    private ParamSettingRow3SecView param_layout3;
    /*** 第4行参数设置 - 运行状态 ***/
    private ParamSettingRow4SecView param_layout4;
    /*** 第5行参数设置 - 其他参数设置 ***/
    private ParamSettingRow5SecView param_layout5;
    /*** 臭气值 ***/
    private AppCompatTextView param_config_other_cqz;
    /*** 第5行参数设置 - 地址更改 ***/
    private ParamSettingRow6SecView lay_setting6;
    /*** 输出控制 ***/
    private SignalOutPanelView sign_out_panel;
    /*** 日志展示 ***/
    private AppCompatTextView tv_log_message;
    /*** 日志开关按钮 ***/
    private Button mOpenLogBtn;
    /*** 保存按钮 ***/
    private Button mSaveBtn;

    /*** 解析收到的投口信息 ***/
    Handler mHandlerQt = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    String obj = (String) msg.obj;
                    if (!StringUtils.isEmpty(obj)) {
                        byte[] bytes_ = ByteUtil.hexStringToBytes(obj);
                        if (bytes_ != null && bytes_.length > 1) {
                            // 06 功能码，轮询信息返回
                            if(bytes_[0] == SingletonSerl.byte_cqz && bytes_[1] == SingletonSerl.byte_gnm_type){
                                if(bytes_.length == 19){
                                    int cqz = ByteUtil.hexStringToInt(ByteUtil.hexBytesToString(new byte[]{bytes_[15], bytes_[16]}));
                                    DecimalFormat df = new DecimalFormat("0.0");//设置保留位数
                                    LOG.e(TAG, "数字："+df.format((float)cqz/10));
                                    param_config_other_cqz.setText("臭气值："+df.format((float)cqz/10)+"ppm");
                                }
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void initView(Bundle savedInstanceState) {
        this.param_layout1 = findViewById(R.id.param_layout1);
        this.param_layout2 = findViewById(R.id.param_layout2);
        this.param_layout3 = findViewById(R.id.param_layout3);
        this.param_layout4 = findViewById(R.id.param_layout4);
        this.param_layout5 = findViewById(R.id.param_layout5);
        this.lay_setting6 = findViewById(R.id.lay_setting6);
        this.param_config_other_cqz = findViewById(R.id.param_config_other_cqz);
        this.sign_out_panel = findViewById(R.id.sign_out_panel);
        this.tv_log_message = findViewById(R.id.tv_log_message);
        this.mSaveBtn = findViewById(R.id.save_btn);
        this.mOpenLogBtn = findViewById(R.id.openLog_btn);
        this.initEvent();

        EventBus.getDefault().register(this);
//        this.param_layout3.parseByte(ByteUtil.hexStringToBytes("050310000100000064000505DC002013888080B8F3"));
    }

    private int getTextViewHeight(TextView view) {
        Layout layout = view.getLayout();
        int desired = layout.getLineTop(view.getLineCount());
        int padding = view.getCompoundPaddingTop() + view.getCompoundPaddingBottom();
        return desired + padding;
    }

    @Subscribe
    public void onEvent(LogEvent event) {
        tv_log_message.append("\n");
        tv_log_message.append("" + event.getValue());

        int offset = getTextViewHeight(tv_log_message);
        if (offset > tv_log_message.getHeight()) {
            tv_log_message.scrollTo(0, offset - tv_log_message.getHeight());
        }
    }

    @Subscribe
    public void onEvent(RunEvent event) {
        String hex = ByteUtil.hexBytesToString(event.getValue());
        Message message = this.mHandlerQt.obtainMessage();
        message.what = 0;
        message.obj = hex;
        this.mHandlerQt.sendMessage(message);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        param_layout3.onDestroy();
        param_layout4.onDestroy();
        param_layout5.onDestroy();
        lay_setting6.onDestroy();
        sign_out_panel.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initEvent() {
        //保存按钮事件
        this.mSaveBtn.setOnClickListener(v -> {
            for (HashMap<String, String> stringStringHashMap : getFormValue()) {
                for (String key : stringStringHashMap.keySet()) {
                    Log.d(TAG, String.format("KEY = %s , VALUE = %s", key, stringStringHashMap.get(key)));
                    SpUtils.putString(getApplicationContext(), key, stringStringHashMap.get(key));
                }
            }
            saveConfig();
            Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();
        });

        LOG.openLog = SpUtils.getBoolean(getApplicationContext(), Constants.OPEN_LOG, false);
        this.mOpenLogBtn.setText(SpUtils.getBoolean(getApplicationContext(), Constants.OPEN_LOG, false) ? "关闭日志" : "打开日志");
        this.mOpenLogBtn.setOnClickListener(v -> {
            boolean open = SpUtils.getBoolean(getApplicationContext(), Constants.OPEN_LOG, false);
            if (open) {
                SpUtils.putBoolean(getApplicationContext(), Constants.OPEN_LOG, false);
                mOpenLogBtn.setText("打开日志");
                Toast.makeText(getApplicationContext(), "日志已关闭", Toast.LENGTH_SHORT).show();
            } else {
                SpUtils.putBoolean(getApplicationContext(), Constants.OPEN_LOG, true);
                mOpenLogBtn.setText("关闭日志");
                Toast.makeText(getApplicationContext(), "日志已打开", Toast.LENGTH_SHORT).show();
            }
            LOG.openLog = !open;
        });
    }

    private void saveConfig() {
        try {
            JSONObject json = new JSONObject();
            json.put(Constants.VIDEO_FILE_NAME, SpUtils.getString(getApplicationContext(), Constants.VIDEO_FILE_NAME, ""));
            json.put(Constants.LEFT_TITLE, SpUtils.getString(getApplicationContext(), Constants.LEFT_TITLE, ""));
            json.put(Constants.DEVICE_ID, SpUtils.getString(getApplicationContext(), Constants.DEVICE_ID, ""));
            json.put(Constants.ACCOUNT, SpUtils.getString(getApplicationContext(), Constants.ACCOUNT, ""));
            json.put(Constants.CITYID, SpUtils.getString(getApplicationContext(), Constants.CITYID, ""));
            json.put(Constants.SERVER_IP, SpUtils.getString(getApplicationContext(), Constants.SERVER_IP, ""));
            json.put(Constants.SERVER_PORT, SpUtils.getString(getApplicationContext(), Constants.SERVER_PORT, ""));
            json.put(Constants.INTERVAL_TIME, SpUtils.getString(getApplicationContext(), Constants.INTERVAL_TIME, ""));
            json.put(Constants.VERSION, SpUtils.getString(getApplicationContext(), Constants.VERSION, ""));
            json.put(Constants.CLOSE_TIME, SpUtils.getString(getApplicationContext(), Constants.CLOSE_TIME, ""));
            json.put(Constants.OPEN_DOOR_END_INTERVAL_TIME, SpUtils.getString(getApplicationContext(), Constants.OPEN_DOOR_END_INTERVAL_TIME, ""));

            LogRecordUtil.replaceTextToFile(json.toString(), Constants.configFile);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private ArrayList<HashMap<String, String>> getFormValue() {
        ArrayList<HashMap<String, String>> values = new ArrayList<>();
        values.addAll(this.param_layout1.getFormValue());
        values.addAll(this.param_layout2.getFormValue());
        values.addAll(this.param_layout3.getFormValue());
        return values;
    }

}
